package pro.shushi.pamirs.hr.core.session;

import org.apache.commons.collections4.CollectionUtils;
import pro.shushi.pamirs.business.api.model.PamirsEmployee;
import pro.shushi.pamirs.business.api.service.PamirsEmployeeService;
import pro.shushi.pamirs.meta.api.CommonApiFactory;
import pro.shushi.pamirs.meta.api.session.PamirsSession;
import pro.shushi.pamirs.user.api.login.UserInfoCache;
import pro.shushi.pamirs.user.api.model.PamirsUser;

import java.util.List;

public class HrSimpleSessionCache {

    private static final ThreadLocal<HrSimpleSessionData> BIZ_DATA_THREAD_LOCAL = new ThreadLocal<>();

    public static PamirsUser getUser() {
        return BIZ_DATA_THREAD_LOCAL.get() == null ? null : BIZ_DATA_THREAD_LOCAL.get().getUser();
    }

    public static PamirsEmployee getEmployee() {
        return BIZ_DATA_THREAD_LOCAL.get() == null ? null : BIZ_DATA_THREAD_LOCAL.get().getEmployee();
    }

    public static void init() {
        Long uid = PamirsSession.getUserId();
        if (uid == null) {
            return;
        }
        PamirsUser user = UserInfoCache.queryUserById(uid);
        if (user != null) {
            HrSimpleSessionData sessionData = new HrSimpleSessionData();
            sessionData.setUser(user);

            List<PamirsEmployee> employees = CommonApiFactory.getApi(PamirsEmployeeService.class).queryListByUid(uid);
            if (CollectionUtils.isNotEmpty(employees)) {
                sessionData.setEmployee(employees.get(0));
            }

            BIZ_DATA_THREAD_LOCAL.set(sessionData);
        }
    }

    public static void clear() {
        BIZ_DATA_THREAD_LOCAL.remove();
    }
}